package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 * @author Dee
 * @date 2023/11/26
 * <p>Description: aio demo
 */
@Slf4j
public class DeeAioDemo {
    public static void main(String[] args) {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("1.txt"),
                StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.info("读取前...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override // 完成后执行
                public void completed(Integer result, ByteBuffer attachment) {
                    buffer.flip();
                    String string = StandardCharsets.UTF_8.decode(buffer).toString();
                    log.info("读取内容:{}", string);
                }

                @Override // 失败执行
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.info("读取后...");
            Thread.sleep(5000);
        } catch (IOException e) {
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
